package com.czy.utils;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Hex;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.security.MessageDigest;

/**
 * @author czy
 * @date 2020-12-17
 * 文件处理工具类
 */
@Slf4j
public class FileUtils {
    public static void main(String[] args) {
//        System.out.println(getSuffixFileName("aa.txt"));
//        String shortText = readShortText("/banner.txt");
        String shortText = readShortText("D:\\file\\测试OA环境-江西五十铃汽车有限公司.pdf");
        System.out.println(shortText);
    }

    /**
     * 读取短文本内容
     * @param classPath
     * @return
     */
    public static String readShortText(String classPath){
        // class 和 classLoader 加载文本的区别 https://www.cnblogs.com/blogtech/p/11151780.html
        //  class加载文件/ 表示classPath路径,因此前面加不加/都一样
        InputStream inputStream = FileUtils.class.getResourceAsStream(classPath);
        // getClassLoader加载文件 / 表示项目根目录 ,因此一般前面不需要/ 用相对路径
//        InputStream inputStream = FileUtils.class.getClassLoader().getResourceAsStream(classPath);
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
        StringBuffer result = new StringBuffer();
        String tempStr;
        try {
            while ((tempStr = bufferedReader.readLine())!=null){
                System.out.println(tempStr);
                result.append(tempStr);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            closeReader(bufferedReader);
        }
        return result.toString();
    }

    /**
     * 保存文件到服务器
     * @param inputStream
     * @param filePath
     */
    public static void saveFileToServer(InputStream inputStream,String filePath){
        if (inputStream==null){
            log.error("输入流为空!");
            return;
        }
        if (StringUtils.isBlank(filePath)){
            log.error("文件存储路径为空!");
            return;
        }
        int len;
        byte[] buf = new byte[1024];
        FileOutputStream fileOutputStream = null;
        try {
            fileOutputStream = new FileOutputStream(filePath);
            while ((len=inputStream.read(buf))!=-1){
                fileOutputStream.write(buf,0,len);
            }
            fileOutputStream.flush();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            closeOutputStream(fileOutputStream);
        }

    }

    /**
     * 文件重命名
     * @param fileName
     * @param isAppend true: 源文件名+时间戳  false: uuid+时间戳
     * @return
     */
    public static String rename(String fileName,boolean isAppend){
        if (StringUtils.isBlank(fileName)){
            return "";
        }
        int i = fileName.lastIndexOf(".");
        //源文件名前缀
        String prefix = fileName.substring(0, i);
        //源文件名后缀
        String suffix = fileName.substring(i);

        if (!isAppend){
            prefix = IdUtils.getUuid().replace("-", "");
        }

        //获取时间戳
        long timestamp = System.currentTimeMillis();

        StringBuilder builder = new StringBuilder();
        builder.append(prefix).append("_").append(timestamp).append(suffix);

        return builder.toString();
    }

    /**
     * 关闭字节输入流
     * @param in
     */
    public static void closeInputStream(InputStream in){
        if (in!=null){
            try {
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 关闭字节输出流
     * @param out
     */
    public static void closeOutputStream(OutputStream out){
        if (out!=null){
            try {
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 关闭字符输入流
     * @param reader
     */
    public static void closeReader(Reader reader){
        if (reader!=null){
            try {
                reader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 关闭字符输出流
     * @param writer
     */
    public static void closeWriter(Writer writer){
        if (writer!=null){
            try {
                writer.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 获取一个文件的md5值(可处理大文件)
     * @return md5 value
     */
    public static String getFileMD5(File file) {
        FileInputStream fileInputStream = null;
        try {
            MessageDigest MD5 = MessageDigest.getInstance("MD5");
            fileInputStream = new FileInputStream(file);
            byte[] buffer = new byte[8192];
            int length;
            while ((length = fileInputStream.read(buffer)) != -1) {
                MD5.update(buffer, 0, length);
            }
            return new String(Hex.encodeHex(MD5.digest()));
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            try {
                if (fileInputStream != null){
                    fileInputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 获取文件名后缀
     * @param fileName
     * @return
     */
    public static String getSuffixFileName(String fileName){
        if (StringUtils.isBlank(fileName)){
            return "";
        }
        int i = fileName.lastIndexOf(".");
        //源文件名后缀
        String suffix = fileName.substring(i);
        return suffix;
    }

    /**
     * MultipartFile 转 File
     * @param file
     * @return
     * @throws Exception
     */
    public static File multipartFileToFile(MultipartFile file) throws Exception {
        File toFile = null;
        if (file.equals("") || file.getSize() <= 0) {
            file = null;
        } else {
            InputStream ins = null;
            ins = file.getInputStream();
            toFile = new File(file.getOriginalFilename());
            inputStreamToFile(ins, toFile);
            ins.close();
        }
        return toFile;
    }

    /**
     * 获取流文件
     * @param ins
     * @param file
     */
    private static void inputStreamToFile(InputStream ins, File file) {
        try {
            OutputStream os = new FileOutputStream(file);
            int bytesRead = 0;
            byte[] buffer = new byte[8192];
            while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
            os.close();
            ins.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //读取json文件
    public static String readJsonFile(String fileName) {
        String jsonStr = "";
        try {
            File jsonFile = new File(fileName);
            FileReader fileReader = new FileReader(jsonFile);
            Reader reader = new InputStreamReader(new FileInputStream(jsonFile),"utf-8");
            int ch = 0;
            StringBuffer sb = new StringBuffer();
            while ((ch = reader.read()) != -1) {
                sb.append((char) ch);
            }
            fileReader.close();
            reader.close();
            jsonStr = sb.toString();
            return jsonStr;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }
}
